import pathlib
from datetime import datetime
import os


def __get_time(type: str = "ft"):
    """【函数】获取当前的日期时间

    type: fp 用于路径，ft 用于文本内容
    """
    current_time = datetime.now()
    if (type == "ft"):
        time_str = datetime.strftime(current_time, "%Y.%m.%d %H:%M:%S")
    elif (type == "fp"):
        time_str = datetime.strftime(current_time, "%Y-%m-%d_%H-%M-%S")
    return time_str


cwd_path = pathlib.Path.cwd()
# raw_file_path = cwd_path / pathlib.Path("./raw_test")
raw_file_path = pathlib.Path(input("Enter your file location: "))
if (raw_file_path.exists() == False):
    raise Exception("\n[ERROR] Path you enter is not exist!\n")
output_folder = raw_file_path.parent / pathlib.Path("./output/")
if (output_folder.exists() == False):
    os.system("mkdir " + str(output_folder))
report_folder = raw_file_path.parent / pathlib.Path("./report/")
if (report_folder.exists() == False):
    os.system("mkdir " + str(report_folder))
report_path = report_folder / pathlib.Path("./Report_" + __get_time(type="fp") + ".txt")


with open(report_path, "w", encoding="utf-8") as rpf:
    rpf.write("Auto Rename Run Report\n")
    rpf.write(__get_time() + "\n")
    rpf.write("Raw Files Floder: " + str(raw_file_path) + "\n")
    rpf.write("Output Folder:    " + str(output_folder) + "\n\n")

for raw_file in raw_file_path.iterdir():
    raw_file_stem_parts = raw_file.stem.split("_")
    new_file_stem = raw_file_stem_parts[0]
    i = 0
    n = len(raw_file_stem_parts)
    log_content = ""
    if (len(raw_file_stem_parts[-1]) == 12):
        while (i < n-2):
            new_file_stem = new_file_stem + "_" + raw_file_stem_parts[i+1]
            i = i + 1
        new_file_name = new_file_stem + raw_file.suffix
        new_file_path = output_folder / pathlib.Path(new_file_name)
        os.rename(raw_file, new_file_path)
        log_content = "Rename:  " + raw_file.name + "  >>  " + new_file_name
    else:
        log_content = "Skip:  " + raw_file.name
        continue

    with open(report_path, "a", encoding="utf-8") as rpf:
        rpf.write(log_content + "\n")
    print(log_content)
